package com.feng.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitConfig {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    /**
     * 定制RabbitTemplate
     */
    @PostConstruct//MyRabbitConfig对象创建完成以后，执行这个方法
    public void initRabbitTemplate(){
        //设置确认回调

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *
             * @param correlationData 当前消息唯一关联数据（这个是消息的唯一id)
             * @param ack 消息是否失败
             * @param cause  失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("confirm"+correlationData);
                System.out.println("b"+ack);
                System.out.println("s"+cause);
            }

        });
        //设置消息抵达队列的回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 只要消息没有投递给指定的队列，就触发这个失败回调
             * @param message  投递失败的消息详细信息
             * @param replaycode 回复的状态码
             * @param replaytext 回复的文本内容
             * @param exchange 当时消息发给哪个交换机
             * @param routingkey 当时消息用哪个路由键
             */
            @Override
            public void returnedMessage(Message message, int replaycode, String replaytext, String exchange, String routingkey) {
                System.out.println(message);
                System.out.println(replaycode);
                System.out.println(replaytext);
                System.out.println(exchange);

            }
        });
    }
}
